package top.lishuoboy.javaweb.a07servlet;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Locale;

/**
 * @author lishuoboy
 * @date 2022-01-06 11:41
 */
@Slf4j
@WebServlet(name = "A03Servlet", value = "/A03Servlet")
public class A03Servlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {

//        resp.reset();               // resp信息全重置，不能用，之前设置的信息都丢是，导致乱码等问题
        resp.setCharacterEncoding(CharsetUtil.UTF_8);

        log.info("==响应头===================================");
        resp.setStatus(200);
        resp.setContentType("text/html;charset=utf-8");    // 前面的 text/json;可根据具体情况选择，一般json居多
        log.info("{}", resp.containsHeader("aaa"));   // false
        resp.setHeader("header1", "header1header1");
        resp.addHeader("header2", "header2header2");
        resp.setDateHeader("date1", System.currentTimeMillis());
        resp.addDateHeader("date2", System.currentTimeMillis());
        resp.setIntHeader("count1", 100);
        resp.addIntHeader("count2", 200);
        ListUtil.list(false, req.getCookies()).forEach(e -> log.info("{}", BeanUtil.beanToMap(e)));
        resp.addCookie(new Cookie("cookie1", "cookie1cookie1"));
        resp.setLocale(Locale.JAPANESE);

//        resp.sendError(401, "未经授权的，未经授权的，未经授权的");   //  自动生成错误页面

        log.info("{}", resp.getBufferSize());  // 8192
//        resp.setBufferSize(10240);
//        resp.resetBuffer();

        log.info("==响应体===================================");
//        resp.setContentLength(3);  // 一般无需主动设置。"你好"共6个字节，设置短了浏览器读取不全
//        resp.getOutputStream().write("你好".getBytes(StandardCharsets.UTF_8));
        resp.getWriter().write("你好");
    }
}
